import os
import jsonpath
import requests
def save_jpg(qun):
    qun_url = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members"   #群管理url
    qun_data = {"gc": qun, "st": 0, "end": 40, "sort": 0, "bkn": "1557973934"}   #群管理参数
    qun_cookie = "tvfe_boss_uuid=289507752e184a87; pgv_pvid=9355379808; pac_uid=0_99055699b0b06; iip=0; RK=bQa481n+XQ; " \
                 "ptcz=32a0048bf48a8a995f66390705f84ef00812325400feef4b752136e2703fddb7; _qpsvr_localtk=0.34572133702731356; " \
                 "uin=o0854795345; skey=@Dnan43fH3; p_uin=o0854795345; pt4_token=sDlwAwzodmnzI2gsUYz9THz51aUtlOT5Y7S4IbOQq5Y_; " \
                 "p_skey=0L5RT70MsY7IesMtPuadDFZBcQ1JAp1*Ad5NiWbKuzs_; traceid=73dc424873"

    qun_members = requests.post(qun_url, qun_data, headers={"cookie": qun_cookie}).json()  #
    uin = jsonpath.jsonpath(qun_members, "$..uin")  # qq号
    card = jsonpath.jsonpath(qun_members, "$..card")  # 群备注名
    nick = jsonpath.jsonpath(qun_members, "$..nick")  # 网名s
    dir = os.path.join(os.getcwd(), str(qun))  # 用当前路径和群名，拼接存放图片的群名文件夹
    print(qun_members)
    # print(uin)
    # print(card)
    # print(nick)
    # print(dir)
    if not os.path.exists(dir):  # 判断文件夹是否已存在
        os.mkdir(dir)  # 创建文件夹
    os.chdir(dir)  # 跳转到该目录下
    for i in range(len(uin)):  # 遍历每个qq号，保存头像
        member_url = "https://q4.qlogo.cn/g?b=qq&nk=%s&s=140" % uin[i]  # 拼接头像照片的url
        req = requests.get(member_url)
        if card[i] == '':
            file_name = "%s.jpg" % nick[i]
        else:
            file_name = "%s.jpg" % card[i]
        with open(file_name, 'wb') as fw:  # 保存图片文件
            fw.write(req.content)


if __name__ == '__main__':
    save_jpg(657659694)